package com.creditease.mobile.news.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class CanvasImageTask extends AsyncTask<ImageView, Void, Bitmap> {

    private ImageView gView;

    protected Bitmap doInBackground(ImageView... views) {
        Bitmap bmp = null;
        ImageView view = views[0];
        // 根据iconUrl获取图片并渲染，iconUrl的url放在了view的tag中。

        if (view.getTag() != null) {
            try {
                URL url = new URL(view.getTag().toString());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream stream = conn.getInputStream();

                bmp = BitmapFactory.decodeStream(stream);
                stream.close();
            } catch (Exception e) {
                Log.v("img", e.getMessage());
                return null;
            }
        }

        this.gView = view;
        return bmp;
    }

    protected void onPostExecute(Bitmap bm) {

        if (bm != null) {
            this.gView.setImageBitmap(bm);
            this.gView = null;
        }
    }
}
